//
//  YZYBindPhoneView.h
//  YZYSDKManagerDemo
//
//  Created by 赵隆杰 on 2024/6/7.
//

#import "YZYBindPhoneView.h"
#import "YZYSDKManagerHeader.h"
#import "ZCFunDataFormat.h"
#import "YZYSaccountStore.h"
#import "ZCNetworkManager.h"

@interface YZYBindPhoneView ()<UITextFieldDelegate>
{
    dispatch_source_t _timer;
}
@property (nonatomic, strong) UIButton *coverView;
@property (nonatomic ,strong) UITextField *mobilePhone;
@property (nonatomic ,strong) UITextField *verificationCode;
@property (nonatomic ,strong) UIButton *verificationBtn;
@property (nonatomic ,strong) UIButton *loginBtn;

@property (nonatomic ,strong) UITextField *firstResponderTextF;//记录将要编辑的输入框
@property (nonatomic, assign) CGFloat self_Height;//保存原始的view高度

@end

@implementation YZYBindPhoneView

- (instancetype)init {
    if (self == [super init]) {
        
        //监听键盘展示和隐藏的通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        
        UIImageView *backbg = [[UIImageView alloc] init];
        backbg.userInteractionEnabled = YES;
        backbg.backgroundColor = [UIColor whiteColor];
        backbg.layer.masksToBounds = YES;
        backbg.layer.cornerRadius = 4;
        [self addSubview:backbg];
        backbg.frame = CGRectMake(0, 0, popupW, popupH);
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = [UIFont boldSystemFontOfSize:24];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.frame = CGRectMake(0, 15, backbg.frame.size.width, 25);
        titleLabel.text = @"绑定手机号";
        [backbg addSubview:titleLabel];
        
        UIButton *backBtn = [[UIButton alloc] init];
        [backbg addSubview:backBtn];
        backBtn.frame = CGRectMake(20, 0, 40, 40);
        [backBtn setTitle:@"返回" forState:UIControlStateNormal];
        [backBtn setTitleColor:yzy_labelColor forState:UIControlStateNormal];
        backBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [backBtn addTarget:self action:@selector(didClickBackBtn) forControlEvents:UIControlEventTouchUpInside];
        
        self.mobilePhone = [[UITextField alloc] init];
        self.mobilePhone.placeholder = @"请输入手机号";
        self.mobilePhone.keyboardType = UIKeyboardTypePhonePad;
        self.mobilePhone.delegate = self;
        self.mobilePhone.font = [UIFont systemFontOfSize:16];
        self.mobilePhone.borderStyle = UITextBorderStyleRoundedRect;
        self.mobilePhone.returnKeyType = UIReturnKeyDone;
        [backbg addSubview:self.mobilePhone];
        self.mobilePhone.frame = CGRectMake(25, CGRectGetMaxY(titleLabel.frame) + 20, backbg.frame.size.width - 50, 40);
        
        self.verificationBtn = [[UIButton alloc] init];
        self.verificationBtn.layer.cornerRadius = 5;
        self.verificationBtn.layer.masksToBounds = YES;
        self.verificationBtn.backgroundColor = yzy_themeColor;
        self.verificationBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [self.verificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.verificationBtn addTarget:self action:@selector(didClickVerification) forControlEvents:UIControlEventTouchUpInside];
        [backbg addSubview:self.verificationBtn];
        self.verificationBtn.frame = CGRectMake(backbg.frame.size.width - 25 - 100, CGRectGetMaxY(self.mobilePhone.frame) + 15, 100, 40);

        self.verificationCode = [[UITextField alloc] init];
        self.verificationCode.placeholder = @"请输入验证码";
        self.verificationCode.keyboardType = UIKeyboardTypeNumberPad;
        self.verificationCode.delegate = self;
        self.verificationCode.font = [UIFont systemFontOfSize:16];
        self.verificationCode.borderStyle = UITextBorderStyleRoundedRect;
        self.verificationCode.returnKeyType = UIReturnKeyDone;
        [backbg addSubview:self.verificationCode];
        self.verificationCode.frame = CGRectMake(25, self.verificationBtn.frame.origin.y, backbg.frame.size.width - 50 - self.verificationBtn.frame.size.width - 10, 40);

        self.loginBtn = [[UIButton alloc] init];
        self.loginBtn.layer.cornerRadius = 5;
        self.loginBtn.layer.masksToBounds = YES;
        self.loginBtn.backgroundColor = yzy_themeColor;
        self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [self.loginBtn setTitle:@"确  定" forState:UIControlStateNormal];
        [self.loginBtn addTarget:self action:@selector(didClickLogin) forControlEvents:UIControlEventTouchUpInside];
        [backbg addSubview:self.loginBtn];
        self.loginBtn.frame = CGRectMake(25, CGRectGetMaxY(self.verificationCode.frame) + 20, backbg.frame.size.width - 50, 40);
        
        UIView *agreeView = [[UIView alloc] init];
        [backbg addSubview:agreeView];
        agreeView.frame = CGRectMake(20, CGRectGetMaxY(self.loginBtn.frame) + 10, backbg.frame.size.width - 50, 22);
        UITextView *agreementTextView = [[UITextView alloc] init];
        agreementTextView.frame = CGRectMake(0, -5, agreeView.frame.size.width, agreeView.frame.size.height);
        [agreeView addSubview:agreementTextView];
        agreementTextView.text = @"* 为完善用户账号体系，首次苹果登录需要绑定手机号";
        agreementTextView.editable = NO;        //必须禁止输入，否则点击将弹出输入键盘
        agreementTextView.scrollEnabled = NO;
        agreementTextView.textColor = [UIColor colorWithRed:155/255.0 green:155/255.0 blue:155/255.0 alpha:1.0];
        agreementTextView.font = [UIFont systemFontOfSize:10];
        
    }
    return self;
}

- (void)didClickBackBtn {
    self.bindPhoneViewBlock(0);
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.coverView removeFromSuperview];
        [self removeFromSuperview];
    });
}

- (void)didClickVerification {
    NSString *phone = self.mobilePhone.text;
    if ([ZCFunDataFormat isBlankString:phone]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"手机号为空"];
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@/%@", YZY_getCode, phone];
    [ZCNetworkManager getWithURL:YZY_AppendUrl(url) Params:nil success:^(id responseObject) {
        NSDictionary *surperdic = (NSDictionary *)responseObject;
        NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
//        NSString *msg = [NSString stringWithFormat:@"%@",surperdic[@"msg"]];
        if ([surpercode isEqualToString:@"200"]) {
            
            [self timeout];
            
        }
    } failure:^(NSString *error) {
        
    }];
    
    
    
}

- (void)didClickLogin {
    
    NSString *phone = self.mobilePhone.text;
    NSString *verificationCode = self.verificationCode.text;
    
    if ([ZCFunDataFormat isBlankString:phone]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"手机号为空"];
        return;
    }
    
    if ([ZCFunDataFormat isBlankString:verificationCode]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"验证码为空"];
        return;
    }
    
    [self stopTimer];
      
    NSDictionary *params = [NSDictionary dictionary];
    params = @{
        @"gameId": [ZCFunDataFormat GetPlatformGameID],
        @"uuid": self.uuid,
        @"isIosLogin": @YES,
        @"iosAuth": self.iosAuth,
        @"phone": phone,
        @"code": verificationCode,
        @"channelNo": [ZCFunDataFormat GetChanneNo]
    };
    [ZCNetworkManager postWithURL:YZY_AppendUrl(YZY_loginByPhone) Params:params success:^(id responseObject) {
        NSDictionary *surperdic = (NSDictionary *)responseObject;
        NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
//        NSString *msg = [NSString stringWithFormat:@"%@",surperdic[@"msg"]];
        NSDictionary *resultDic = [NSDictionary dictionaryWithDictionary:surperdic[@"data"]];
        if ([surpercode isEqualToString:@"200"]) {
            NSString *accessToken = [ZCFunDataFormat filterString:resultDic[@"accessToken"]];
            if (![ZCFunDataFormat isBlankString:accessToken]) {
                [[YZYSaccountStore sharedInstance] saveAccessToken:accessToken];
            }
            self.bindPhoneViewBlock(1);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.coverView removeFromSuperview];
                [self removeFromSuperview];
            });
            
        }
        
    } failure:^(NSString *error) {
        
    }];
}

- (void)timeout {
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(self->_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置（倒计时结束后调用）
                [self.verificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                //设置可点击
                self.verificationBtn.userInteractionEnabled = YES;
                self.verificationBtn.backgroundColor = yzy_themeColor;
                
            });
        } else {
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [self.verificationBtn setTitle:[NSString stringWithFormat:@"重新获取(%@')",strTime] forState:UIControlStateNormal];
                //设置不可点击
                self.verificationBtn.userInteractionEnabled = NO;
                self.verificationBtn.backgroundColor = [UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1.0];
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);
}

/**
 *  停止倒计时
 */
- (void)stopTimer {
    if (_timer) {
        //销毁定时器
        dispatch_source_cancel(_timer);
    }
    
    //获取验证码按钮恢复初始状态
    [self.verificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    //设置可点击
    self.verificationBtn.userInteractionEnabled = YES;
    self.verificationBtn.backgroundColor = yzy_themeColor;
}

//- (void)dealloc {
//    _timer = nil;
//}

- (void)show {
    [[YZYSaccountStore sharedInstance] getCurrentWindowWithCompletion:^(UIWindow *window) {
        if (window) {
            UIButton *coverView = [[UIButton alloc] init];
            coverView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3f];
            [coverView addTarget:self action:@selector(coverViewClick) forControlEvents:UIControlEventTouchUpInside];
            self.coverView = coverView;
            coverView.frame = window.bounds;
            
            UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
            UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
            visualView.alpha = 0.0;
            [coverView addSubview:visualView];
            visualView.frame = coverView.frame;
            
            [window addSubview:coverView];
            
            self.frame = CGRectMake(0, 0, popupW, popupH);
            self.layer.cornerRadius = 12.0f;
            self.center = CGPointMake(window.center.x, window.center.y);
            if (![ZCFunDataFormat GetIsLandscape]) {
                self.center = CGPointMake(window.center.x, window.center.y - 40);
            }
            self.self_Height = self.frame.origin.y;
            [window addSubview:self];
        }
    }];
}

- (void)coverViewClick {
    [self endEditing:YES];
}

- (void)closeView {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.coverView removeFromSuperview];
        [self removeFromSuperview];
    });
}

- (void)dealloc{
    _timer = nil;
    //移除键盘通知监听者
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if ([self.firstResponderTextF isFirstResponder])[self.firstResponderTextF resignFirstResponder];
}
#pragma maek UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    self.firstResponderTextF = textField;//当将要开始编辑的时候，获取当前的textField
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark : UIKeyboardWillShowNotification/UIKeyboardWillHideNotification
- (void)keyboardWillShow:(NSNotification *)notification{
    CGRect rect = [self.firstResponderTextF.superview convertRect:self.firstResponderTextF.frame toView:self];//获取相对于self.view的位置
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];//获取弹出键盘的fame的value值
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self convertRect:keyboardRect fromView:self.window];//获取键盘相对于self.view的frame ，传window和传nil是一样的
    CGFloat keyboardTop = keyboardRect.origin.y;
    NSNumber * animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];//获取键盘弹出动画时间值
    NSTimeInterval animationDuration = [animationDurationValue doubleValue];
    if (keyboardTop < CGRectGetMaxY(rect)) {//如果键盘盖住了输入框
        CGFloat gap = keyboardTop - CGRectGetMaxY(rect) - 10;//计算需要网上移动的偏移量（输入框底部离键盘顶部为10的间距）
        __weak typeof(self)weakSelf = self;
        [UIView animateWithDuration:animationDuration animations:^{
            weakSelf.frame = CGRectMake(weakSelf.frame.origin.x, gap, weakSelf.frame.size.width, weakSelf.frame.size.height);
        }];
    }
    
}
- (void)keyboardWillHide:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSNumber * animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];//获取键盘隐藏动画时间值
    NSTimeInterval animationDuration = [animationDurationValue doubleValue];
    if (self.frame.origin.y < 0) {//如果有偏移，当影藏键盘的时候就复原
        __weak typeof(self)weakSelf = self;
        [UIView animateWithDuration:animationDuration animations:^{
            weakSelf.frame = CGRectMake(weakSelf.frame.origin.x, weakSelf.self_Height, weakSelf.frame.size.width, weakSelf.frame.size.height);
        }];
    }
}


@end
